package hibernateDAOS;

import hibernate.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


import beans.Mozo;
import beans.Plato;
import beans.Rubro;

public class PlatoDAO {
	
	private static PlatoDAO instancia = null;
	private static SessionFactory sf = null;

	public static PlatoDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new PlatoDAO();
		} 
		return instancia;
	}
	
	public void guardarPlato(Plato p){
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(p);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void eliminarPlato(Plato p){
		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(p);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void modificarPlato(Plato m){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(m);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<Object[]> obtenerPlatosXRubroObject(String rubro){
		Session session = sf.openSession();
		String query = ""; 
		
		if (rubro.equals(""))query = "from Plato ";
		else query = "from Plato  where rubro.nombreRubro = '"+rubro+"'";
		
		Query q = session.createQuery(query);
		List<Plato> platos = q.list();
		session.close();
		List<Object[]> os = new ArrayList<Object[]>();
		Object[] o ;
		int cant=0;
		for(Plato p : platos){
			o = new Object[platos.size()];
			o[0] = p.getIdPlato();
			o[1] = p.getNombrePlato();
			o[2] = p.getPrecio();
			if( p.getRubro() != null)
			{
				o[3] = p.getRubro().getNombreRubro();
			}
			os.add(o);
		}
		return os;
	}
	@SuppressWarnings("unchecked")
	public List<Plato> obtenerPlatosXRubro(String rubro){
		Session session = sf.openSession();
		Query q = session.createQuery("from Plato where rubro.nombreRubro = '"+rubro+"'");
		List<Plato> platos = q.list();
		session.close();
		return platos;
	}
	
	public List<Plato> obtenerTodosPlatos(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Plato");
		List<Plato> platos = q.list();
		session.close();
		return platos;
	}
	
	@SuppressWarnings("unchecked")
	public Plato obtenerPlato(Plato m){
		Session session = sf.openSession();
		session.load(m, m.getIdPlato());
		session.close();
		return m;
	}
	

}


